import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jxchmz/%E8%93%9D%E7%89%99/BleManager.dart';
import 'package:jxchmz/%E8%AE%BE%E5%A4%87%E8%BF%9E%E6%8E%A5/DeviceConnect.dart';
import 'package:jxchmz/API/%E5%BA%93%E5%AD%98%E7%AE%A1%E7%90%86/KuCunManager.dart';
import 'package:jxchmz/API/%E9%94%80%E5%94%AE%E7%AE%A1%E7%90%86/SaleManage.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';
import 'package:jxchmz/Setting.dart';

import '../../BleModel.dart';

class GoodsLuRu extends StatefulWidget {
  @override
  _GoodsLuRuState createState() => new _GoodsLuRuState();
}

class _GoodsLuRuState extends State<GoodsLuRu> {
  //物资类别
  TextEditingController GoodsTypeController = new TextEditingController();
  //入库日期
  TextEditingController DateController = new TextEditingController();
  //物资
  TextEditingController GoodsController = new TextEditingController();
  //物资类别选择数据名称集合
  List GoodsTypeData = [];
  // 选择的物资类别信息名称
  var SelectGoodsTypeName = "";
  //物资类别数据列表
  List GoodsTypeList = [];
  //物资类别选择id
  var GoodsTypeId ;

  //物资选择数据名称集合
  List GoodsData = [];
  // 选择的物资信息名称
  var SelectGoodsName = "";
  //物资数据列表
  List GoodsList = [];
  //物资选择id
  var GoodsId ;


  //是否读取标识
  var IsRead = false;
  //录入列表
  var EPCList = [];
  //去重用的数组,防止重复请求
  var EPCListRequest = [];
   DeviceConnect deviceConnect = new DeviceConnect();
   BluetoothCharacteristic? _bluetoothCharacteristicFFF1 ;
  BluetoothCharacteristic? _bluetoothCharacteristicFFF2 ;
  var IsConnect = false;

  /// 图像文件对象
  File? _image;
  /// ImagePicker 引擎实例
  final picker = ImagePicker();

//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //获取蓝牙连接状态
    //获取当前日期
    String now = new DateTime.now().toString();
    DateController =new TextEditingController(text: now.substring(0,10));
    Future.delayed(Duration.zero,() async {
      //获取连接池
      List<BluetoothDevice>? devideList =await  BleManager.instance.getConnectedDevices();
      GetStorage getStorage = new GetStorage();
      if(devideList!.length>0){
        IsConnect = true;
        _bluetoothCharacteristicFFF1 = BleModel.BletoothCharacteristicFFF1;
        _bluetoothCharacteristicFFF2 = BleModel.BletoothCharacteristicFFF2;
        GetlistGoods();
        //获取物资类别
        GetlistGoodsType();
        //设置监听蓝牙数据
        _characteristicFFF4SetNotify();
      }else{
        IsConnect = false;
        //弹窗阻止
        ShowNo();
      }

    });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(IsConnect){
      _bluetoothCharacteristicFFF1!.setNotifyValue(false);
      BleManager.instance.CancelListen();
    }
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
      backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text("物资录入", style: TextStyle(fontSize: 15, color: Colors.black),),
          centerTitle: true,
          elevation: 0,
          actions: [
            IconButton(onPressed: (){
              if(IsRead){
                //停止读取
                IsRead = false;
                List<int> WritData = [0x40,0x02,0xE1,0x00];
                int Check = checkSum(WritData);
                WritData.add(Check);
                WriteBle(WritData);
              }
              setState(() {
              });
            //功率调整
              _bluetoothCharacteristicFFF1!.setNotifyValue(false);
              Get.to(Setting())!.then((value){
                print("返回数据");
                //设置页面返回的数据
                // 重新监听蓝牙
                _bluetoothCharacteristicFFF1!.setNotifyValue(true);
              });
            }, icon: Icon(Icons.settings)),
            IconButton(onPressed: (){
              // ShowUpload();

            }, icon: Icon(Icons.cloud_upload)),
          ],
          iconTheme: IconThemeData(
              color: Colors.black
          ),
        ),
        body: Container(
          padding: EdgeInsets.all(15),
          child: Column(
            children: [

              //物料名称
              GestureDetector(
                child: TextField(
                  controller: GoodsController,
                  enabled: false,
                  decoration: InputDecoration(
                      hintText: "请选择物资",
                      suffixIcon: Icon(Icons.keyboard_arrow_down),
                      icon: Container(
                        width:70,
                        child: Text("物资"),
                      )
                  ),
                ),
                onTap: (){
                  if(GoodsList.isEmpty){
                    GetxTools().WaringToast("暂无可选物资");
                    return;
                  }
                  print("开始选择物资");
                  //打开选择物资类别
                  ShowPickGoods();
                },
              ),
              //物资类别
              GestureDetector(
                child: TextField(
                  controller: GoodsTypeController,
                  enabled: false,
                  decoration: InputDecoration(
                      hintText: "请先选择物资",
                      // suffixIcon: Icon(Icons.keyboard_arrow_down),
                      icon: Container(
                        width:70,
                        child: Text("物资类别"),
                      )
                  ),
                ),
                // onTap: (){
                //   if(GoodsTypeList.isEmpty){
                //     GetxTools().WaringToast("暂无可选物资类别");
                //     return;
                //   }
                //   print("开始选择物资类别");
                //   //打开选择物资类别
                //   ShowPickGoodsType();
                // },
              ),
              //入库日期
              TextField(
                controller: DateController,
                enabled: false,
                decoration: InputDecoration(
                    icon: Container(
                      width:70,
                      child: Text("入库日期"),
                    )
                ),
              ),
              //图片上传
              Column(

                children: [
                  Container(
                    child: Text("图片上传"),
                    alignment: Alignment.centerLeft,
                  ),
                   GestureDetector(
                     child: Container(
                       alignment: Alignment.center,
                       child:_image==null?Image.asset("Image/xiangji.png",width: 70,height: 70,):Image.file(_image!,height: 100,fit: BoxFit.contain,),
                     ),
                     onTap: (){
                       //点击拍照
                       getImage();
                     },
                   ),
                  _image==null?Container(
                    child: Text("点击拍照"),
                  ):Container(),
                ],
              ),
              Container(
                height: 15,
              ),
              //录入列表
              Container(
                alignment: Alignment.centerLeft,
                child: Text(
                  "录入列表(${EPCList.length})",
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20),
                ),
              ),
              Expanded(
                child: ListView.separated(
                  itemCount: EPCList.length,
                  itemBuilder: (context, index) {
                    return Container(
                      child: ListTile(
                        title:  Container(
                          child: Text("RFID编号:${EPCList[index]}"),
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return Divider();
                  },
                ),
              ),
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    MaterialButton(
                      child: Text(
                        "清空数据",
                        style: TextStyle(color: Colors.white),
                      ),
                      minWidth: MediaQuery.of(context).size.width / 3,
                      color: Colors.orange,
                      shape: const RoundedRectangleBorder(
                        //边框圆角
                        borderRadius: BorderRadius.all(
                          Radius.circular(20),
                        ),
                      ),
                      onPressed: () {
                        //清空数据
                        EPCList.clear();
                        EPCListRequest.clear();
                        setState(() {
                        });
                      },
                    ),
                    MaterialButton(
                      child: Text(IsRead ? "停止读取" : "开始读取", style: TextStyle(color: Colors.white)),
                      minWidth: MediaQuery.of(context).size.width / 2 ,
                      color: IsRead ? Colors.red : Colors.blue,
                      shape: const RoundedRectangleBorder(
                        //边框圆角
                        borderRadius: BorderRadius.all(
                          Radius.circular(20),
                        ),
                      ),
                      onPressed: () {
                        if(IsRead){
                          //停止读取
                          IsRead = false;
                          List<int> WritData = [0x40,0x02,0xE1,0x00];
                          int Check = checkSum(WritData);
                          WritData.add(Check);
                          WriteBle(WritData);
                        }else{
                          //开始读取
                          IsRead = true;
                          List<int> WritData = [0x40,0x02,0xE1,0x01];
                          int Check = checkSum(WritData);
                          WritData.add(Check);
                          WriteBle(WritData);
                        }
                        setState(() {
                        });
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        )
    );
  }
  //没有连接蓝牙，弹窗阻止
  ShowNo(){
    Get.defaultDialog(
        title: "提示",
        middleText: "请连接蓝牙设备!",
        barrierDismissible: false,
        confirm: MaterialButton(
          onPressed: () async {
           Get.back();
           Get.back();
          },
          child: Text("确定",style: TextStyle(color: Colors.white),),
          color: Color(0xff372D9F),
        ),
         );
  }


  //弹窗物资类别
  ShowPickGoodsType(){
    Pickers.showSinglePicker(
      context,
      // 使用只有Name的数组
      data: GoodsTypeData,
      selectData: SelectGoodsTypeName,
      onConfirm: (p, position) {
        // 提取所选的数据id
        GoodsTypeId = GoodsTypeList[position]['id'];
        //所选的名称
        SelectGoodsTypeName = p;
        //给输入框赋值
        GoodsTypeController = new TextEditingController(text: p);
        print("选择的物资类别id:$GoodsTypeId");
        setState(() {});
      },
    );
  }
  //弹窗物资
  ShowPickGoods(){
    Pickers.showSinglePicker(
      context,
      // 使用只有Name的数组
      data: GoodsData,
      selectData: SelectGoodsName,
      onConfirm: (p, position) {
        // 提取所选的数据id
        GoodsId = GoodsList[position]['id'];
        //所选的名称
        SelectGoodsName = p;
        //给输入框赋值
        GoodsController = new TextEditingController(text: p);
        print("选择的物资类别id:$GoodsId");
        
        //给物料分类赋值
        GoodsTypeId = GoodsList[position]['categoryId'];
        SelectGoodsTypeName = GoodsList[position]['categoryIdName'];
        GoodsTypeController = new TextEditingController(text: SelectGoodsTypeName);
        setState(() {});
      },
    );
  }
  //获取物资类别
  GetlistGoodsType() async {
    GoodsTypeList = [];
    var ResponseData = await KuCunManager().GetGoodsType();
    if(ResponseData['code'] == 200){
      GoodsTypeList = ResponseData['data'];
      // 单独提取产品名称
      for (var p = 0; p < GoodsTypeList.length; p++) {
        GoodsTypeData.add(GoodsTypeList[p]['name']);
      }
    }else {
      new GetxTools().ErrorToast("物资类别信息获取失败!");
    }
    setState(() {});
  }
  //获取物资
  GetlistGoods() async {
    GoodsList = [];
    var ResponseData = await KuCunManager().GetGoods();
    if(ResponseData['code'] == 200){
      GoodsList = ResponseData['rows'];
      // 单独提取产品名称
      for (var p = 0; p < GoodsList.length; p++) {
        GoodsData.add(GoodsList[p]['name']);
      }
    }else {
      new GetxTools().ErrorToast("物资信息获取失败!");
    }
    setState(() {});
  }
  //监听特征上报数据
  _characteristicFFF4SetNotify() async {
    await   _bluetoothCharacteristicFFF1!.setNotifyValue(true);
    // ignore: missing_return
    BleManager.instance.listenCharacteristicValue(_bluetoothCharacteristicFFF1!, (data) async {
      if (data == null) {
        print("data=null>>>>>>");
        return;
      }
      //解析蓝牙数据，转为十六进制
      String DataHex =await _BleDataCallback(data);
      List dataList = DataHex.split(",");

      if(dataList[0]=="f0"&&dataList[2]=="e1"){
        print("DataHex=>>>>>>$DataHex");
        print("dataList=>>>>>>$dataList");
        print("是epc");
        //这里面写调用逻辑
        //拿epc数据
        //判断EPC长度
       int Len = _hexToInt(dataList[1].toString());
       print("EPC数据长度:$Len");
        String EPC = dataList.sublist(3,Len+1).join("");
        print("epc:$EPC");
        if(!EPCListRequest.contains(EPC)){
          EPCListRequest.add(EPC);
          //查询标签信息是否在库内
         // await SearchRFID(EPC);
        }
        print("EPC:$EPCList");

      }
      if(DataHex.contains("f1,03,01")){
        print("录入页面蓝牙数据");
        //  读卡状态
        if(DataHex.contains("f1,03,01,00")){
          //停止读卡
          IsRead = false;
        }else{
          IsRead = true;
        }
      }
      if (mounted) {
        setState(() {
        });
      }
    });

  }
  //  发送请求
  void WriteBle(WritData) {
    // print("发送的蓝牙数据:${WritData}");
    BleManager.instance.characteristicToWriteValue(_bluetoothCharacteristicFFF2!, WritData).then((value) => print("write result:$value"));
  }
  //解析蓝牙数据
  _BleDataCallback(value) async {
    List data = [];
    for (var i = 0; i < value.length; i++) {
      String dataStr = value[i].toRadixString(16);
      if (dataStr.length < 2) {
        dataStr = "0" + dataStr;
      }
      String dataEndStr =  dataStr;
      data.add(dataEndStr);
    }
    return data.join(",");
  }
  //校验位
  int checkSum(List<int> buffer) {
    int sum = 0;
    for (int i = 0; i < buffer.length; i++) {
      sum += buffer[i];
    }
    sum = (~sum) + 1;
    return sum;
  }


//获取照片方法
  Future getImage() async {
    // 获取图像的核心方法
    final pickedFile = await picker.getImage(source: ImageSource.camera);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }
//查询标签信息是否在库内
//   SearchRFID(EPC) async {
//     print("开始请求获取标签信息");
//     var data = {
//       "rfidCode":EPC,
//     };
//     var ResultData = await new SaleManage().SearchEPC(data);
//     if(ResultData['code'] == 200){
//       if(ResultData['total']==0){
//         EPCList.add(EPC);
//
//       }
//     }else {
//     }
//     EPCList= EPCList.toSet().toList();
//     setState(() {});
//   }
  //物资录入提交
  // UploadLuRuConfrim() async {
  //   var data = {
  //     "materialId":GoodsId,
  //     "jxcMaterialCategoryId":GoodsTypeId,
  //     "rfidCodeStatus":0,
  //     "rfidCodeList":EPCList,
  //     "imageUrl":""
  //   };
  //   KSProgressDialog().LoadingToast("录入中...", context);
  //   var ResultData = await new SaleManage().UploadLuRu(data);
  //   KSProgressDialog().CloseLoading();
  //   if(ResultData['code'] == 200){
  //      GetxTools().SuccessToast("录入成功!");
  //      Clear();
  //   }else {
  //      GetxTools().ErrorToast("录入失败!");
  //   }
  //   setState(() {});
  //
  //
  //
  // }
  //十六进制转十进制
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }

  // ShowUpload(){
  //   //清空本地缓存，前往登录页面
  //   Get.defaultDialog(
  //       title: "提示",
  //       middleText: "确定要上传此数据吗？",
  //       barrierDismissible: false,
  //       confirm: MaterialButton(
  //         onPressed: () async {
  //           UploadLuRuConfrim();
  //           Get.back();
  //         },
  //         child: Text("确定",style: TextStyle(color: Colors.white),),
  //         color: Color(0xff372D9F),
  //       ),
  //       cancel: MaterialButton(
  //         onPressed: () {
  //           Get.back();
  //         },
  //         child: Text(
  //           "取消",
  //           style: TextStyle(color: Color(0xff372D9F)),
  //         ),
  //         color: Colors.white,
  //         //边框样式
  //         shape: const RoundedRectangleBorder(
  //           //边框颜色
  //           side: BorderSide(
  //             color: Color(0xff372D9F),
  //             width: 1,
  //           ),
  //         ),
  //       ));
  // }
//  清空数据
Clear(){
    EPCList.clear();
    EPCListRequest.clear();
}

}
